package com.xuan.friend.service.user.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuan.api.RemoteJudgeService;
import com.xuan.api.domain.UserExeResult;
import com.xuan.api.domain.dto.JudgeSubmitDTO;
import com.xuan.api.domain.vo.UserQuestionResultVo;
import com.xuan.common.core.constants.Constants;
import com.xuan.common.core.enums.ProgramType;
import com.xuan.common.core.enums.QuestionResType;
import com.xuan.common.core.enums.ResultCode;
import com.xuan.common.core.exception.BusinessException;
import com.xuan.common.core.utils.ThreadLocalUtils;
import com.xuan.friend.domain.question.Question;
import com.xuan.friend.domain.question.QuestionCase;
import com.xuan.friend.domain.question.es.QuestionES;
import com.xuan.friend.domain.question.vo.QuestionDetailVo;
import com.xuan.friend.domain.user.UserSubmit;
import com.xuan.friend.domain.user.dto.UserSubmitDTO;
import com.xuan.friend.elasticsearch.QuestionRepository;
import com.xuan.friend.mapper.question.QuestionMapper;
import com.xuan.friend.mapper.user.UserSubmitMapper;
import com.xuan.friend.rabbit.JudgeProducer;
import com.xuan.friend.service.user.UserQuestionService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author ASUS
 * @description 针对表【tb_user_submit(用户提交表)】的数据库操作Service实现
 * @createDate 2024-12-04 16:42:35
 */
@Service
public class UserQuestionServiceImpl extends ServiceImpl<UserSubmitMapper, UserSubmit>
        implements UserQuestionService {

    @Resource
    private QuestionRepository questionRepository;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private RemoteJudgeService remoteJudgeService;

    @Resource
    private JudgeProducer judgeProducer;

    @Resource
    private UserSubmitMapper userSubmitMapper;

    @Override
    public UserQuestionResultVo submit(UserSubmitDTO userSubmitDTO) {
        // 1. 先判断提交的代码类型
        // 2. 查询题目是否存在
        // 3. 调用判题服务执行代码并获取执行结果
        // 4. 根据返回结果，判断执行是否通过
        Long questionId = userSubmitDTO.getQuestionId();
        Integer programType = userSubmitDTO.getProgramType();
        // 1. 查询题目是否存在,不存在则查询数据库并存入 elasticsearch
        QuestionES questionES = getQuestionES(questionId);
        // 2. 判断提交的代码类型
        if (ProgramType.JAVA.getValue().equals(programType)) {
            // 组装调用 判题服务 所需的参数
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(questionES, userSubmitDTO);
            // 调用判题服务执行代码并获取执行结果
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        throw new BusinessException("当前暂时只支持 Java 代码哦");
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO userSubmitDTO) {
        Long questionId = userSubmitDTO.getQuestionId();
        Integer programType = userSubmitDTO.getProgramType();
        if (!ProgramType.JAVA.getValue().equals(programType)) {
            throw new BusinessException("当前暂时只支持 Java 代码哦");
        }
        // 查询题目是否存在,不存在则查询数据库并存入 elasticsearch
        QuestionES questionES = getQuestionES(questionId);
        // 组装调用 判题服务 所需的参数
        JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(questionES, userSubmitDTO);
        // 向队列投递消息(会被转化为 json 字符串的形式进行投递)
        judgeProducer.sendMessage(judgeSubmitDTO);
        return true;
    }

    @Override
    public UserQuestionResultVo getExeResult(Long questionId, Long contestId, String currentTime) {
        Long userId = ThreadLocalUtils.get(Constants.USER_ID, Long.class);
        UserSubmit userSubmit = userSubmitMapper.selectOne(new LambdaQueryWrapper<UserSubmit>()
                .eq(UserSubmit::getQuestionId, questionId)
                .eq(UserSubmit::getUserId, userId)
                .eq(contestId != null, UserSubmit::getContestId, contestId)
                .isNull(contestId == null, UserSubmit::getContestId)
                // 判题结果需满足: 产生时间 > 当前时间
                .gt(StringUtils.isNotBlank(currentTime), UserSubmit::getCreateTime, currentTime));
        UserQuestionResultVo userQuestionResultVo = new UserQuestionResultVo();
        if (userSubmit == null) {
            userQuestionResultVo.setPass(QuestionResType.IN_JUDGE.getValue());
            return userQuestionResultVo;
        }

        userQuestionResultVo.setPass(userSubmit.getPass());
        userQuestionResultVo.setExeMessage(userSubmit.getExecMessage());
        String caseJudgeRes = userSubmit.getCaseJudgeRes();
        List<UserExeResult> userExeResultList = JSONUtil.toList(caseJudgeRes, UserExeResult.class);
        userQuestionResultVo.setUserExeResultList(userExeResultList);
        userQuestionResultVo.setScore(userSubmit.getScore());
        return userQuestionResultVo;

    }

    @Override
    public QuestionDetailVo questionReset(Long questionId, Long contestId) {
        QuestionES questionES = getQuestionES(questionId);
        QuestionDetailVo questionDetailVo = new QuestionDetailVo();
        BeanUtils.copyProperties(questionES, questionDetailVo);

        Long userId = ThreadLocalUtils.get(Constants.USER_ID, Long.class);
        CompletableFuture.runAsync(() -> {
            // 将 tb_user_submit 中
            UserSubmit userSubmit = userSubmitMapper.selectOne(new LambdaQueryWrapper<UserSubmit>()
                    .eq(UserSubmit::getUserId, userId)
                    .eq(UserSubmit::getQuestionId, questionId)
                    .isNull(contestId == null, UserSubmit::getContestId)
                    .eq(contestId != null, UserSubmit::getContestId, contestId));
            if (userSubmit == null) {
                return;
            }
            userSubmit.setUserCode(questionES.getDefaultCode());
            userSubmitMapper.updateById(userSubmit);
        });
        return questionDetailVo;
    }


    @NotNull
    private QuestionES getQuestionES(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        if (questionES == null) {
            // 查询数据库看题目是否存在
            Question question = questionMapper.selectById(questionId);
            if (question == null) {
                throw new BusinessException(ResultCode.FAILED_NOT_EXISTS, "题目不存在");
            }
            questionES = new QuestionES();
            BeanUtils.copyProperties(question, questionES);
            questionRepository.save(questionES);
        }
        return questionES;
    }

    @NotNull
    private static JudgeSubmitDTO assembleJudgeSubmitDTO(QuestionES questionES, UserSubmitDTO userSubmitDTO) {
        Long questionId = userSubmitDTO.getQuestionId();
        Long contestId = userSubmitDTO.getContestId();
        String userCode = userSubmitDTO.getUserCode();
        Integer programType = userSubmitDTO.getProgramType();
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();

        Long userId = ThreadLocalUtils.get(Constants.USER_ID, Long.class);
        judgeSubmitDTO.setUserId(userId);
        judgeSubmitDTO.setContestId(contestId);
        judgeSubmitDTO.setQuestionId(questionId);
        judgeSubmitDTO.setProgramType(programType);
        judgeSubmitDTO.setDifficulty(questionES.getDifficulty());
        judgeSubmitDTO.setTimeLimit(questionES.getTimeLimit());
        judgeSubmitDTO.setSpaceLimit(questionES.getSpaceLimit());
        judgeSubmitDTO.setUserCode(userCode);
        // 拼装 main 函数和用户输入代码
        judgeSubmitDTO.setExecCode(getCodeContent(questionES, userCode));
        // 组装测试用例的输入和输出
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).toList();
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setInputList(inputList);
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }

    @NotNull
    private static String getCodeContent(QuestionES questionES, String userCode) {
        String mainFunc = questionES.getMainFunc();
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex == -1) {
            throw new BusinessException("运行失败,请重新检查代码格式");
        }
        userCode = userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        return userCode;
    }
}




